// templates/deliver/pages/location/location.js
import Notify from '@vant/weapp/notify/notify';
const app = getApp();


Page({

    /**
     * 页面的初始数据
     */
    data: {
        count: 0,
        area: '', //获取区域
        scale: 12.1,
        activeNames: ['1'],// 打开信息 按钮
        latitude: 0,   //获取当前位置
        longitude: 0,
        checked: true,
        image: '/templates/deliver/img/business.png',
        markers: [],
        dataAll: [],
        view_delivery_man_id: 0,
        view_driver_name: '',
        view_delivery_district_id: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

        var delivery_man = wx.getStorageSync('delivery_man'); //读取缓存

        let view_delivery_man_id = wx.getStorageSync('view_delivery_man_id') || 0
        let view_driver_name = ''
        let view_delivery_district_id = 0
        if (view_delivery_man_id > 0) {
            view_driver_name = wx.getStorageSync('view_driver_name')
            view_delivery_district_id = wx.getStorageSync('view_delivery_district_id')
        }

        this.setData({
            view_delivery_man_id,
            view_driver_name,
            view_delivery_district_id
        })

        console.log(user)
        var _this = this; //获取this
        wx.getLocation({
                type: "gcj02",
                success(res) {
                    _this.setData({
                        latitude: res.latitude,
                        longitude: res.longitude,
                     })
                }
            }),
            this.setData({
                area: delivery_man.area
            })

            _this.index();

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
       


    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
       
       

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },
    onDisplay({
        detail
    }) {
        console.log({
            detail
        })
        var markers = this.data.markers;
        wx.showModal({
            title: '提示',
            content: '是否切换开关？',
            success: (res) => {
                console.log(res.confirm)
                if (!detail) {
                    for (var i = 0; i < markers.length; i++) {
                        this.setData({
                            ["markers[" + i + "].callout.display"]: 'BYCLICK',
                            checked: detail
                        });
                    }
                    this.setData({
                        checked: detail
                    });
                } else {
                    for (var i = 0; i < markers.length; i++) {
                        this.setData({
                            ["markers[" + i + "].callout.display"]: 'ALWAYS',

                        });
                    }
                    this.setData({
                        checked: detail
                    });
                }

            },
        });
    },

    onChangeShowCallout(event) {

        const {
            value
        } = event.detail;
        console.log(value)
        this.data.markers.forEach((item, index) => {

            if (value) {
                this.setData({

                    ["markers[" + index + "].callout.display"]: 'ALWAYS'

                });
            } else {
                this.setData({

                    ["markers[" + index + "].callout.display"]: 'BYCLICK'

                });
            }

        })


    },
    index() {
        var _this = this;
        var area = this.data.area;
        wx.request({
            url: app.globalData.URL + '/deliver.Order/getNotAreaOrder',
            method: 'GET',
            data: {
                mall_id: app.globalData.mall_id,
                area: area,
            },

            success(res) {
                
               
                var listData = res.data.data;
                if (res.data.data.code == 0) {
                    Notify(res.data.data.message);
                    _this.setData({
                        markers: [],
                        dataAll: []
                    })
                } else {
                    var markers = [];
                    var dataAll = [];
                    var newdataAll = [];
                    //地图渲染位置定位
                    for (var i = 0; i < listData.length; i++) {
                        markers = markers.concat({
                            iconPath: "../../img/icon-hc.png",
                            id: listData[i].id,
                            latitude: listData[i].longitude,
                            longitude: listData[i].latitude,

                            width: 23,
                            height: 23,
                            callout: {
                                content: listData[i].name,
                                fontSize: 14,
                                padding: true,
                                color: '#444',
                                display: 'ALWAYS',
                                textAlign: 'center',
                                borderRadius: 5,
                                bgColor: '#ffffff'
                            },
                        })
                        //重组后端数据
                        dataAll = dataAll.concat({
                            address: listData[i].address,
                            pay_time: listData[i].pay_time,
                            id: listData[i].id,
                            latitude: listData[i].longitude,
                            longitude: listData[i].latitude,
                            mobile: listData[i].mobile,
                            name: listData[i].name,
                            order_no: listData[i].order_no,
                            remark: listData[i].remark,
                            sale_status: listData[i].sale_status,
                            seller_remark: listData[i].seller_remark,
                            total_goods_price: listData[i].total_goods_price,
                            words: listData[i].words,
                            resKm: _this.getDistance(_this.data.latitude, _this.data.longitude, listData[i].longitude, listData[i].latitude),

                       })
                     
                    }
                   
                    //根据距离排序
                    newdataAll = _this.sortArr(dataAll);
                    
                   _this.setData({
                        markers: markers,
                        dataAll: newdataAll
                    })
                    console.log(listData);
                    Notify({
                        type: 'success',
                        message: '数据加载完成'
                    });
                   
                }

            }
        })
    },
    //根据距离计算远近
    sortArr(newArray) {
        var arr = newArray;
        var s = "";
        for (var i = 1; i < arr.length; i++) {
          for (var j = i; j > 0; j--) {
            if (arr[j].resKm > arr[j - 1].resKm) {
              s = arr[j];
              arr[j] = arr[j - 1];
              arr[j - 1] = s;
            }
          }
        }
       return newArray.reverse();
       
      },
    // 经纬度计算距离

    getDistance( lat1,  lng1,  lat2,  lng2){
        var radLat1 = lat1*Math.PI / 180.0;
        var radLat2 = lat2*Math.PI / 180.0;
        var a = radLat1 - radLat2;
        var  b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
        Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
        s = s *6378.137 ;// EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        s = s.toFixed(2);
       
        return parseFloat(s);
    },


    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
       this.index();
       wx.stopPullDownRefresh()

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
       
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    //点击导航事件
    getLocation(e) {
        var id = e.currentTarget.dataset['id']; //获取传递的参数
        var address = this.data.dataAll[id].address; //获取地址
        var name = this.data.dataAll[id].name; //获取name
        var mobile = this.data.dataAll[id].mobile; //获取手机号
        var latitude = this.data.dataAll[id].latitude; //获取精度
        var longitude = this.data.dataAll[id].longitude //获取纬度
        wx.openLocation({
            latitude: Number(latitude), //要去的纬度-地址 一定不要使数字
            longitude: Number(longitude), //要去的经度-地址
            address: address,
            name: name + '/' + mobile,
            scale: 15
        })


    },
    //点击展开
    onAddress(event) {
        this.setData({
          activeNames: event.detail,
        });
      },
      orderBydata(event){
           var order_id = event.target.dataset.id;
           var name = event.target.dataset.name;
            wx.navigateTo({
              url: '/templates/deliver/pages/order/order?order_id='+ order_id+'&name='+name,
            })
      }
})